package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryParam;
import com.tanhua.domain.vo.RecommendUserVo;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class RecommendService {

    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity queryTodayBest() {
//        1、查询mongo 返回RecommendUser
        RecommendUser recommendUser = recommendUserApi.queryTodayBest(UserHolder.getUserId());
        if(recommendUser==null){
            recommendUser = new RecommendUser();
//            recommendUser.setUserId(RandomUtils.nextLong(1,99));
            recommendUser.setUserId(2L);
            recommendUser.setScore(RandomUtils.nextDouble(90,99));
        }
//        2、根据RecommendUser中的Userid查询UserInfo
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
//        RecommendUser+UserInfo===》RecommendUserVo
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo,recommendUserVo);
        if(userInfo.getTags()!=null){
            recommendUserVo.setTags( userInfo.getTags().split(","));
        }
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());
        return ResponseEntity.ok(recommendUserVo);
    }

    public ResponseEntity queryRecommendation(RecommendUserQueryParam param) {

        PageResult pageResult = recommendUserApi.queryRecommendation(UserHolder.getUserId(),  param.getPage(),param.getPagesize()); //Integer page,Integer pagesize,int counts,List list
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();

        if(CollectionUtils.isEmpty(items)){
            for (int i = 0; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(RandomUtils.nextLong(1,99));
                recommendUser.setScore(RandomUtils.nextDouble(80,90));
                items.add(recommendUser);
            }
        }
//        items.sort(new Comparator<RecommendUser>() {
//            @Override
//            public int compare(RecommendUser o1, RecommendUser o2) {
//                return o2.getScore().intValue() - o1.getScore().intValue();
//            }
//        });

        items.sort((o1,o2)->{
            return o2.getScore().intValue()-o1.getScore().intValue();
        });



        //        1、查询mongo 返回RecommendUser
        //        2、根据RecommendUser中的Userid查询UserInfo

        List<RecommendUserVo> list = new ArrayList<>();

        for (RecommendUser recommendUser : items) {
            Long userId = recommendUser.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo,recommendUserVo);
            if(userInfo.getTags()!=null){
                recommendUserVo.setTags( userInfo.getTags().split(","));
            }
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());
            list.add(recommendUserVo);
        }

        pageResult.setItems(list);
//        3.构建recommendUserVo

        return ResponseEntity.ok(pageResult);

    }

    public ResponseEntity queryPersonalInfo(Long userId) {
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        UserInfo userInfo = userInfoApi.findById(userId);
        BeanUtils.copyProperties(userInfo,recommendUserVo);
        if(userInfo.getTags()!=null){
            recommendUserVo.setTags(userInfo.getTags().split(","));
        }

//        select * from recommend_user where toUserId=UserHolder.getUserId() and userId=userId

        Long score = recommendUserApi.queryScore(UserHolder.getUserId(),userId);

        recommendUserVo.setFateValue(score); //缘分值 当前登录人和 userId的缘分值

        return ResponseEntity.ok(recommendUserVo);
    }



    public ResponseEntity queryStrangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return ResponseEntity.ok(question==null?"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？":question.getTxt());

    }

    public ResponseEntity replyStrangerQuestions(Long userId, String reply) {
//        通过环信发送一个消息 。谁UserHolder.getUserId() 向谁 userId发 什么消息
//        {
//            "userId": "1", //当前登录人的ID
//             "nickname":"黑马小妹",  //当前登录人昵称
//             "strangerQuestion": "你喜欢去看蔚蓝的大海还是去爬巍峨的高山？", // 陌生人问题
//            "reply": "我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~" //当前登录的回复内容
//        }

        Map<String,String> sendMsg = new HashMap();
        sendMsg.put("userId",UserHolder.getUserId().toString());
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        sendMsg.put("nickname",userInfo.getNickname());

        Question question = questionApi.findByUserId(userId);
        sendMsg.put("strangerQuestion",question==null?"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？":question.getTxt());
        sendMsg.put("reply",reply);

        String jsonMsg = JSON.toJSONString(sendMsg);

        huanXinTemplate.sendMsg(userId.toString(),jsonMsg);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity cards(int num) {
        PageResult pageResult = recommendUserApi.queryRecommendation(UserHolder.getUserId(), 1,num); //Integer page,Integer pagesize,int counts,List list
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();

        if(CollectionUtils.isEmpty(items)){
            for (int i = 0; i < 20; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(RandomUtils.nextLong(1,99));
                recommendUser.setScore(RandomUtils.nextDouble(80,90));
                items.add(recommendUser);
            }
        }

        List<RecommendUserVo> list = new ArrayList<>();

        for (RecommendUser recommendUser : items) {
            Long userId = recommendUser.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo,recommendUserVo);
            if(userInfo.getTags()!=null){
                recommendUserVo.setTags( userInfo.getTags().split(","));
            }
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());
            list.add(recommendUserVo);
        }


        return ResponseEntity.ok(list);

    }

    @DubboReference
    private UserLikeApi userLikeApi;

//    右滑喜欢
    public ResponseEntity love(Long likeUserId) {
//        1、写入到user_like表中
        userLikeApi.save(UserHolder.getUserId(),likeUserId);
//        2、判断对方是否喜欢自己 select * from user_like where userId= likeUserId and likeUserId=UserHolder.getUserId()
        boolean isExist = userLikeApi.isExist(likeUserId,UserHolder.getUserId());
//        3如果对方不喜欢自己 就直接删除当前推荐的数据
        if(isExist){
            //  4、如果喜欢
            friendApi.save(UserHolder.getUserId(),likeUserId);
//        huanXinTemplate.contactUsers(UserHolder.getUserId(),likeUserId);// TODO ,正式上线时放开
        }

        recommendUserApi.delete(likeUserId,UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }


    public ResponseEntity unlove(Long userId) {
//        删除推荐数据 delete from recommend_user where userId={userId} and toUserId=UserHolder.getUserid()
        recommendUserApi.delete(userId,UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }


}
